
package protocol.transactions;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import protocol.XoneProtocol;
import protocol.XoneServiceCode;
import protocol.meta.Source;
import protocol.meta.Subject;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import com.netease.http.THttpRequest;

public class SearchSubjectAndSourceTransaction extends XoneBaseTransaction {

    private int mType;
    private String mQueryString;

    public SearchSubjectAndSourceTransaction(int type, String queryString) {
        super(XoneBaseTransaction.TRANSACTION_TYPE_SEARCH_SUBJECT_AND_SOURCE);
        mType = type;
        mQueryString = queryString;
    }

    @Override
    public void onTransact() {
        THttpRequest request = XoneProtocol.getInstance().createSearchRequest(mType, mQueryString);
        sendRequest(request);
    }

    @Override
    protected void onXoneTransactionSuccess(int code, Object obj) {
        if (obj != null && obj instanceof JsonElement) {
            Gson gson = new Gson();
            List<Subject> subjectList;
            List<Source> sourceList;

            JsonElement subjectListElement = ((JsonElement)obj).getAsJsonObject().get("subjectList");
            JsonElement sourceListElement = ((JsonElement)obj).getAsJsonObject().get("sourceList");

            Type subjectListType = new TypeToken<List<Subject>>(){}.getType();
            Type sourceListType = new TypeToken<List<Source>>(){}.getType();

            subjectList = gson.fromJson(subjectListElement, subjectListType);
            sourceList = gson.fromJson(sourceListElement, sourceListType);

            List<Object> o = new ArrayList<Object>();
            o.add(subjectList);
            o.add(sourceList);
            notifyMessage(XoneServiceCode.TRANSACTION_SUCCESS, o);
        } else {
            // TODO
            // notifyError(errCode, arg3)
        }
    }

    @Override
    protected void onXoneTransactionError(int errCode, Object obj) {
        notifyError(errCode, obj);
    }

}
